package com.pucheng.bracelet.app.ble;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.text.TextUtils;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleMtuChangedCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleReadCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.pucheng.bracelet.app.util.ByteUtils;
import com.pucheng.bracelet.app.util.UuidUtils;
import com.pucheng.bracelet.app.util.WriteUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by dingjikerbo on 2016/8/27.
 */
public class ClientManager {

//    private static BleManager mClient;

//    public static BleManager getClient() {
//        if (mClient == null) {
//            synchronized (ClientManager.class) {
//                if (mClient == null) {
//                    mClient = BleManager.getInstance();
//                }
//            }
//        }
//        return mClient;
//    }

    private static ClientManager bleClienManage;
    private int mtu = 0;
    private Map<String, Boolean> mapNotifyState = new HashMap<>();

    private String bleMac = "";

    public static ClientManager getInstance() {
        if (bleClienManage == null) {
            synchronized (ClientManager.class) {
                bleClienManage = new ClientManager();
            }
        }
        return bleClienManage;
    }

    private ClientManager() {
    }

    private BleDevice bleDevice;

    public void startScan(final BleScanCallback bleScanCallback) {

        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                LogUtils.e("开始扫描蓝牙");
                if (bleScanCallback != null) {
                    bleScanCallback.onScanStarted(success);
                }
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                if (!TextUtils.isEmpty(bleDevice.getName())) {
                    LogUtils.e("bleDeviceName = " + bleDevice.getName());
                }
                if (BleUtils.isPctek(bleDevice.getScanRecord())) {
//                    BleManager.getInstance().cancelScan();
                    if (bleScanCallback != null) {
                        bleScanCallback.onScanning(bleDevice);
                    }
                }

            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                if (bleScanCallback != null) {
                    bleScanCallback.onScanFinished(scanResultList);
                }
            }
        });
    }

    /**
     * 与设备配对 参考源码：platform/packages/apps/Settings.git
     * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
     */
    static public boolean createBond(Class btClass, BluetoothDevice btDevice)
            throws Exception {
        Method createBondMethod = btClass.getMethod("createBond");
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
        return returnValue.booleanValue();
    }

    public void startScan(String mac, BleScanAndConnectCallback bleScanAndConnectCallback) {
        BleManager.getInstance().scanAndConnect(new com.clj.fastble.callback.BleScanAndConnectCallback() {
            @Override
            public void onScanFinished(BleDevice scanResult) {
                LogUtils.e("Ble Scan Finished");
            }

            @Override
            public void onStartConnect() {

            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                ToastUtils.showLong("蓝牙扫描失败，BleException=" + exception.toString());
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {

            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {

            }

            @Override
            public void onScanStarted(boolean success) {
                LogUtils.e("开始扫描蓝牙");
                if (bleScanAndConnectCallback != null) {
                    bleScanAndConnectCallback.onScanStarted(success);
                }
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
                if (!TextUtils.isEmpty(bleDevice.getName()) && !TextUtils.isEmpty(bleDevice.getMac())) {
                    BleLog.e("bleDeviceName = " + bleDevice.getName());

                    if (bleDevice.getMac().equals(mac)) {
                        BleManager.getInstance().cancelScan();
                        connect(bleDevice.getMac(), new BleGattCallback() {
                            @Override
                            public void onStartConnect() {

                            }

                            @Override
                            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                                if (bleScanAndConnectCallback != null) {
                                    bleScanAndConnectCallback.onConnectFail(bleDevice, exception);
                                }
                            }

                            @Override
                            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                                ClientManager.this.bleDevice = bleDevice;
                                if (bleScanAndConnectCallback != null) {
                                    bleScanAndConnectCallback.onConnectSuccess(bleDevice, gatt, status);
                                }
                            }

                            @Override
                            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                                if (bleScanAndConnectCallback != null) {
                                    bleScanAndConnectCallback.onDisConnected(isActiveDisConnected, bleDevice, gatt, status);
                                }

                            }
                        });
                    }
                }
            }

            @Override
            public void onScanning(BleDevice bleDevice) {

            }

        });
    }

    public void connect(String mac, BleGattCallback bleConnectCallback) {
        LogUtils.e("Mac = "+mac);
        if (TextUtils.isEmpty(mac)){
            return;
        }
        BleDevice bleDevice = new BleDevice(BleManager.getInstance().getBluetoothAdapter().getRemoteDevice(mac));
        BleManager.getInstance().disconnectAllDevice();
        try {
            boolean isSucces = ClsUtils.createBond(bleDevice.getDevice().getClass(), bleDevice.getDevice());
            LogUtils.e("isSucces:" + isSucces);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("配对异常：" + e.getMessage());
        }
        BleManager.getInstance().connect(mac, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                if (bleConnectCallback != null) {
                    bleConnectCallback.onStartConnect();
                }
                LogUtils.e("开始连接");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                if (bleConnectCallback != null) {
                    bleConnectCallback.onConnectFail(bleDevice, exception);
                }
                LogUtils.e("连接失败：" + exception.toString());
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                if (bleConnectCallback != null) {
                    bleConnectCallback.onConnectSuccess(bleDevice, gatt, status);
                }
                ClientManager.getInstance().bleDevice = bleDevice;
                ClientManager.getInstance().bleMac = bleDevice.getMac();
//                getCharacteristic(bleDevice, "180f", "2a19");
                LogUtils.e("连接成功：name=" + ClientManager.getInstance().bleDevice.getName() + "   mac:" + ClientManager.getInstance().bleDevice.getMac());
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                if (bleConnectCallback != null) {
                    bleConnectCallback.onDisConnected(isActiveDisConnected, bleDevice, gatt, status);
                }
                LogUtils.e("断开连接，status" + status);
            }
        });
//            }
//        };
//        new Thread(runnable).start();
    }

    /**
     * 根据UUID获取服务
     *
     * @param bleDevice 蓝牙
     * @param uuid      UUID
     * @return 服务
     */
    public BluetoothGattService getGttaService(BleDevice bleDevice, String uuid) {
        if (BleManager.getInstance().isConnected(bleDevice.getMac())) {
            BluetoothGatt gatt = BleManager.getInstance().getBluetoothGatt(bleDevice);
            LogUtils.e("serViceUUID: " + UUID.fromString(UuidUtils.uuid16To128(uuid)));
            return gatt.getService(UUID.fromString(UuidUtils.uuid16To128(uuid)));
        }
        return null;
    }

    /**
     * 获取指定的Characteristic
     *
     * @param bleDevice          蓝牙
     * @param serviceUUID        服务UUID
     * @param characteristicUUID CharacteristicUUID
     * @return 服务
     */
    public BluetoothGattCharacteristic getCharacteristic(BleDevice bleDevice, String serviceUUID, String characteristicUUID) {
        if (BleManager.getInstance().isConnected(bleDevice.getMac())) {
            LogUtils.e("characteristicUUID: " + UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)));
            return getGttaService(bleDevice, serviceUUID).getCharacteristic(UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)));
        }
        return null;
    }


    /**
     * 读取数据
     *
     * @param bleDevice          蓝牙
     * @param bleDevice          蓝牙
     * @param serviceUUID        服务UUID
     * @param characteristicUUID CharacteristicUUID
     */
    public void readData(BleDevice bleDevice, String serviceUUID, String characteristicUUID, MyBleReadCallback myBleReadCallback) {
        BleManager.getInstance().read(
                bleDevice,
                UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString(),
                UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString(),
                new BleReadCallback() {

                    @Override
                    public void onReadSuccess(final byte[] data) {
                        if (myBleReadCallback != null) {
                            myBleReadCallback.onReadSuccess(data);
//                            myBleReadCallback.onReadSuccess(HexUtil.formatHexString(data));
                        }

                    }

                    @Override
                    public void onReadFailure(final BleException exception) {

                    }
                });
    }

    public void sendCmd(String serviceUUID, String characteristicUUID, String cmd, BleWriteCallback bleWriteCallback) {
        if (bleDevice == null || !BleManager.getInstance().isConnected(bleMac)){
            connect(bleMac, new BleGattCallback() {
                @Override
                public void onStartConnect() {

                }

                @Override
                public void onConnectFail(BleDevice bleDevice, BleException exception) {

                }

                @Override
                public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                    sendCmd(serviceUUID,characteristicUUID,cmd,bleWriteCallback);
                }

                @Override
                public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {

                }
            });
            return;
        }
        String serviceUUIDs = UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString();
        String witerUUID = UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString();
        BleManager.getInstance().write(bleDevice,
                serviceUUIDs,
                witerUUID, WriteUtils.getWriteBytes(cmd), new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        log("发送指令成功：\ncurrent:" + current + "\ntotal:" + total + "\njustWrite" + HexUtil.formatHexString(justWrite, true));
                        if (bleWriteCallback != null) {
                            bleWriteCallback.onWriteSuccess(current, total, justWrite);
                        }
                    }

                    @Override
                    public void onWriteFailure(BleException exception) {
                        log("发送指令失败：" + exception.toString());
                        if (bleWriteCallback != null) {
                            bleWriteCallback.onWriteFailure(exception);
                        }
                    }
                });


    }

    /**
     * 发送操作指令
     *
     * @param cmd              指令
     * @param bleWriteCallback 回调
     */
    public void sendControlCmd(String cmd, BleWriteAndNotifyCallback bleWriteCallback) {
        sendCmd(BleUUId.UUID_3802, BleUUId.UUID_5A00, cmd, bleWriteCallback);
    }

    public void sendCmd(String serviceUUID, String characteristicUUID, String cmd, BleWriteAndNotifyCallback bleWriteCallback) {
        if (bleDevice == null || !BleManager.getInstance().isConnected(bleDevice)){
//            ToastUtils.showLong("您还未连接蓝牙，请先连接蓝牙");
            return;
        }
//        BleManager.getInstance().no
//        if (mapNotifyState.containsKey(characteristicUUID)) {
//            if (mapNotifyState.get(characteristicUUID)){
//                wirteCmd(serviceUUID, characteristicUUID, cmd, bleWriteCallback);
//                return;
//            }
//        }
        BleManager.getInstance().notify(
                bleDevice,
                UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString(),
                UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString(),
                new BleNotifyCallback() {

                    @Override
                    public void onNotifySuccess() {
                        log("打开通知成功");
                        mapNotifyState.put(characteristicUUID, true);
                        wirteCmd(serviceUUID, characteristicUUID, cmd, bleWriteCallback);
                    }

                    @Override
                    public void onNotifyFailure(final BleException exception) {
                        log("打开通知失败：" + exception.toString());
                        mapNotifyState.put(characteristicUUID, false);
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        log("收到消息：\nserviceUUID:" + serviceUUID + "\ncharacteristicUUID:" + characteristicUUID + "\ndata:" + HexUtil.formatHexString(data));
                        if (bleWriteCallback != null) {
                            bleWriteCallback.onCharacteristicChanged(data);
                        }

                    }
                });

    }

    public void wirteCmd(String serviceUUID, String characteristicUUID, String cmd, BleWriteAndNotifyCallback bleWriteCallback) {
        BleManager.getInstance().write(bleDevice,
                UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString(),
                UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString(), WriteUtils.getWriteBytes(cmd), new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        log("发送指令成功：\ncurrent:" + current + "\ntotal:" + total + "\njustWrite" + HexUtil.formatHexString(justWrite, true));
                        if (bleWriteCallback != null) {
                            bleWriteCallback.onWriteSuccess(current, total, justWrite);
                        }
                    }

                    @Override
                    public void onWriteFailure(BleException exception) {
                        log("发送指令失败：" + exception.toString());
                        if (bleWriteCallback != null) {
                            bleWriteCallback.onWriteFailure(exception);
                        }
                    }
                });
    }

    /**
     * 更新表盘
     *
     * @param res              表盘数据
     * @param bleWriteCallback 回调
     */
    public void upClockDial(byte res[], BleWriteAndNotifyCallback bleWriteCallback) {
//         = FileIOUtils.readFile2BytesByStream(path);
        String serviceUUID = BleUUId.UUID_3A04;
        String characteristicUUID = BleUUId.UUID_7A00;
        BleManager.getInstance().notify(
                bleDevice,
                UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString(),
                UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString(),
                new BleNotifyCallback() {

                    @Override
                    public void onNotifySuccess() {
                        log("打开通知成功");
                        BleManager.getInstance().write(bleDevice,
                                UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString(),
                                UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString(), WriteUtils.getUpDataCmdByte(ByteUtils.subBytes(res, 0, 12)), new BleWriteCallback() {
                                    @Override
                                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                                        log("发送指令成功：\ncurrent:" + current + "\ntotal:" + total + "\njustWrite" + HexUtil.formatHexString(justWrite, true));
                                        if (bleWriteCallback != null) {
                                            bleWriteCallback.onWriteSuccess(current, total, justWrite);
                                        }
                                    }

                                    @Override
                                    public void onWriteFailure(BleException exception) {
                                        log("发送指令失败：" + exception.toString());
                                        if (bleWriteCallback != null) {
                                            bleWriteCallback.onWriteFailure(exception);
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onNotifyFailure(final BleException exception) {
                        log("打开通知失败：" + exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        log("收到消息：\nserviceUUID:" + serviceUUID + "\ncharacteristicUUID:" + characteristicUUID + "\ndata:" + HexUtil.formatHexString(data));
                        if (bleWriteCallback != null) {
                            bleWriteCallback.onCharacteristicChanged(data);
                        }
                        if (data[1] == -4 && data[2] == 0x01) {
                            if (mtu == 0) {
                                BleManager.getInstance().setMtu(bleDevice, 512, new BleMtuChangedCallback() {
                                    @Override
                                    public void onSetMTUFailure(BleException exception) {
                                        LogUtils.e("onSetMTUFailure:" + exception.toString());
                                    }

                                    @Override
                                    public void onMtuChanged(int mtu) {
                                        LogUtils.e("mtuSize:" + mtu);
                                        ClientManager.this.mtu = mtu;
                                        int sumNum = res.length / (mtu - 3);
                                        if (res.length % (mtu - 3) != 0) {
                                            sumNum++;
                                        }
                                        String quickViewPeriod = "";
                                        quickViewPeriod.replaceAll(":", "").replaceAll("-", "").trim();
                                        upDataRessoure(ByteUtils.subBytes(res, 12, res.length - 12), mtu - 3, 0, sumNum);
                                    }
                                });
                            } else {
                                int sumNum = res.length / (mtu - 3);
                                if (res.length % (mtu - 3) != 0) {
                                    sumNum++;
                                }
                                upDataRessoure(ByteUtils.subBytes(res, 12, res.length - 12), mtu - 3, 0, sumNum);
                            }
                        }

                    }
                });

    }

    public void upData(String path, BleWriteAndNotifyCallback bleWriteCallback) {
        byte res[] = FileIOUtils.readFile2BytesByStream(path);
        String serviceUUID = BleUUId.UUID_3A04;
        String characteristicUUID = BleUUId.UUID_7A00;
        BleManager.getInstance().notify(
                bleDevice,
                UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString(),
                UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString(),
                new BleNotifyCallback() {

                    @Override
                    public void onNotifySuccess() {
                        log("打开通知成功");
                        BleManager.getInstance().write(bleDevice,
                                UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString(),
                                UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString(), WriteUtils.getUpDataCmdByte(ByteUtils.subBytes(res, 0, 12)), new BleWriteCallback() {
                                    @Override
                                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                                        log("发送指令成功：\ncurrent:" + current + "\ntotal:" + total + "\njustWrite" + HexUtil.formatHexString(justWrite, true));
                                        if (bleWriteCallback != null) {
                                            bleWriteCallback.onWriteSuccess(current, total, justWrite);
                                        }
                                    }

                                    @Override
                                    public void onWriteFailure(BleException exception) {
                                        log("发送指令失败：" + exception.toString());
                                        if (bleWriteCallback != null) {
                                            bleWriteCallback.onWriteFailure(exception);
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onNotifyFailure(final BleException exception) {
                        log("打开通知失败：" + exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        log("收到消息：\nserviceUUID:" + serviceUUID + "\ncharacteristicUUID:" + characteristicUUID + "\ndata:" + HexUtil.formatHexString(data));
                        if (bleWriteCallback != null) {
                            bleWriteCallback.onCharacteristicChanged(data);
                        }
                        if (data[1] == -4 && data[2] == 0x01) {
                            if (mtu == 0) {
                                BleManager.getInstance().setMtu(bleDevice, 512, new BleMtuChangedCallback() {
                                    @Override
                                    public void onSetMTUFailure(BleException exception) {
                                        LogUtils.e("onSetMTUFailure:" + exception.toString());
                                    }

                                    @Override
                                    public void onMtuChanged(int mtu) {
                                        LogUtils.e("mtuSize:" + mtu);
                                        ClientManager.this.mtu = mtu;
                                        int sumNum = res.length / (mtu - 3);
                                        if (res.length % (mtu - 3) != 0) {
                                            sumNum++;
                                        }
                                        String quickViewPeriod = "";
                                        quickViewPeriod.replaceAll(":", "").replaceAll("-", "").trim();
                                        upDataRessoure(ByteUtils.subBytes(res, 12, res.length - 12), mtu - 3, 0, sumNum);
                                    }
                                });
                            } else {
                                int sumNum = res.length / (mtu - 3);
                                if (res.length % (mtu - 3) != 0) {
                                    sumNum++;
                                }
                                upDataRessoure(ByteUtils.subBytes(res, 12, res.length - 12), mtu - 3, 0, sumNum);
                            }
                        }

                    }
                });

    }

    private void sendMsgData(byte[] res, int mtuSize, final int index, final int sumNum) {
        if (index < sumNum) {
            LogUtils.e("正在传输第" + (index + 1) + "数据，共" + sumNum + "包数据");
            sendData(WriteUtils.getUpDataByte(res, mtuSize, index), BleUUId.UUID_3805, BleUUId.UUID_5A01, new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    if (index < sumNum) {
                        sendMsgData(res, mtuSize, index + 1, sumNum);
                    } else {
                        LogUtils.e("消息推送完成！");
                    }
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        } else {
            LogUtils.e("消息推送完成！");
        }


    }

    public void sendMsg(byte[] cmd, byte[] msg, BleWriteAndNotifyCallback bleWriteCallback) {
        if (bleDevice == null){
            LogUtils.e("手环断开连接！");
            return;
        }
        String serviceUUID = BleUUId.UUID_3805;
        String characteristicUUID = BleUUId.UUID_5A01;
        BleManager.getInstance().notify(
                bleDevice,
                UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString(),
                UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString(),
                new BleNotifyCallback() {

                    @Override
                    public void onNotifySuccess() {
                        log("打开通知成功");
                        BleManager.getInstance().write(bleDevice,
                                UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString(),
                                UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString(), cmd, new BleWriteCallback() {
                                    @Override
                                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                                        log("发送指令成功：\ncurrent:" + current + "\ntotal:" + total + "\njustWrite" + HexUtil.formatHexString(justWrite, true));
                                        if (bleWriteCallback != null) {
                                            bleWriteCallback.onWriteSuccess(current, total, justWrite);
                                        }
                                    }

                                    @Override
                                    public void onWriteFailure(BleException exception) {
                                        log("发送指令失败：" + exception.toString());
                                        if (bleWriteCallback != null) {
                                            bleWriteCallback.onWriteFailure(exception);
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onNotifyFailure(final BleException exception) {
                        log("打开通知失败：" + exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        log("收到消息：\nserviceUUID:" + serviceUUID + "\ncharacteristicUUID:" + characteristicUUID + "\ndata:" + HexUtil.formatHexString(data));
                        if (bleWriteCallback != null) {
                            bleWriteCallback.onCharacteristicChanged(data);
                        }
                        if (mtu == 0) {
                            BleManager.getInstance().setMtu(bleDevice, 512, new BleMtuChangedCallback() {
                                @Override
                                public void onSetMTUFailure(BleException exception) {
                                    LogUtils.e("onSetMTUFailure:" + exception.toString());
                                }

                                @Override
                                public void onMtuChanged(int mtu) {
                                    LogUtils.e("mtuSize:" + mtu);
                                    ClientManager.this.mtu = mtu;
                                    int sumNum = msg.length / (mtu - 3);
                                    if (msg.length % (mtu - 3) != 0) {
                                        sumNum++;
                                    }
                                    String quickViewPeriod = "";
                                    quickViewPeriod.replaceAll(":", "").replaceAll("-", "").trim();
                                    sendMsgData(msg, mtu - 3, 0, sumNum);
                                }
                            });
                        } else {
                            int sumNum = msg.length / (mtu - 3);
                            if (msg.length % (mtu - 3) != 0) {
                                sumNum++;
                            }
                            sendMsgData(msg, mtu - 3, 0, sumNum);
                        }
                    }
                });

    }

    private void upDataRessoure(byte[] res, int mtuSize, final int index, final int sumNum) {
//        byte sendByte[] = WriteUtils.getUpDataByte(ByteUtils.subBytes(res,12,res.length-12),mtu-3);
        if (index < sumNum) {
            LogUtils.e("正在传输第" + (index + 1) + "数据，共" + sumNum + "包数据");
            sendData(WriteUtils.getUpDataByte(res, mtuSize, index), BleUUId.UUID_3A04, BleUUId.UUID_7A00, new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    if (index < sumNum) {
                        upDataRessoure(res, mtuSize, index + 1, sumNum);
                    } else {
                        LogUtils.e("手环资源更新完毕！");
                    }
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        } else {
            LogUtils.e("手环资源更新完毕！");
        }


    }

    public void sendData(byte data[], String serviceUUID, String characteristicUUID, BleWriteCallback bleWriteCallback) {
        BleManager.getInstance().write(bleDevice,
                UUID.fromString(UuidUtils.uuid16To128(serviceUUID)).toString(),
                UUID.fromString(UuidUtils.uuid16To128(characteristicUUID)).toString(), data, false, new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        log("发送指令成功：\ncurrent:" + current + "\ntotal:" + total + "\njustWrite" + HexUtil.formatHexString(justWrite, true));
                        if (bleWriteCallback != null) {
                            bleWriteCallback.onWriteSuccess(current, total, justWrite);
                        }
                    }

                    @Override
                    public void onWriteFailure(BleException exception) {
                        log("发送指令失败：" + exception.toString());
                        if (bleWriteCallback != null) {
                            bleWriteCallback.onWriteFailure(exception);
                        }
                    }
                });
    }

    private void log(String msg) {
        LogUtils.e("蓝牙操作：" + msg);
    }

}
